package com.example.chatonline.service;

import com.example.chatonline.pojo.User;
import com.example.chatonline.pojo.UserDto;
import com.example.chatonline.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    public boolean register(UserDto userDto) {
        if(userRepository.existsByuserName(userDto.getUserName())){
            return true;
        }

        // 创建新用户
        User user = new User();
        user.setUserName(userDto.getUserName());
        user.setPassword(passwordEncoder.encode(userDto.getPassword())); // 加密密码
        userRepository.save(user); // 保存用户到数据库
        return false;
    }

    public boolean login(UserDto userDto) {
        Optional<User> userOptional = userRepository.findByuserName(userDto.getUserName());
        if (userOptional.isEmpty()) {
            return false; // 用户不存在
        }

        User user = userOptional.get();
        // 验证密码
        return passwordEncoder.matches(userDto.getPassword(), user.getPassword());
    }
}
